<template>
  <div class="avatar-uploader">
    <input
      type="file"
      ref="fileToUpload"
      style="display:none"
      :accept="accept"
      :multiple="false"
      @change="onFileAdded"
    />

    <div class="avatar" @click="selectFile()">
      <el-avatar
        v-if="avatarUrl"
        class="img"
        shape="square"
        :size="size"
        fit="fill"
        @error="avatarError"
        :src="avatarUrl"
      ></el-avatar>
      <el-avatar
        v-else
        class="img"
        shape="square"
        :size="size"
        fit="fill"
        src="/static/img/uploader/no-image.png"
      ></el-avatar>
    </div>
    <div class="notice">图片仅支持“.jpg,.jpeg,.png,.gif”，不可大于4M。</div>
  </div>
</template>

<script>
import UploadFile from './UploadFile'
export default {
  name: 'avatarUploader',
  data() {
    return {
      accept: '.jpg,.jpeg,.png,.gif',
      avatarUrl: '',
      maxSize: 2097152
    }
  },
  props: {
    avatar: {
      type: String,
      required: false,
      default: ''
    },
    size: {
      type: Number,
      required: false,
      default: 120
    },
    name: {
      type: String,
      required: false
    }
  },
  methods: {
    selectFile() {
      this.$refs.fileToUpload.click()
    },
    async getOSS() {
      let url = '/sys/oss/imguptoken'
      let res = await this.$http({
        url: this.$http.adornUrl(url),
        method: 'post'
      })
      return res.data
    },
    async onFileAdded(event) {
      let oss = await this.getOSS()
      let [token, domain, files] = [oss.token, oss.domain, event.target.files]

      let file = files[0]
      if (file.size > this.maxSize) {
        let msg = file.name + '文件大小超出限制'
        this.$alert(msg, '上传失败')
        return
      }
      this.upload(file, token, domain)
    },
    async upload(file, token, domain) {
      var uploadFile = new UploadFile(file, token, domain)
      uploadFile.upload({
        onSuccess: file => {
          this.avatarUrl = file.url
          this.$emit('uploaded', {
            name: file.name,
            url: file.url
          })
        },
        onError: _ => {
          this.$notify.error({ title: '失败', message: '上传头像失败' })
        }
      })
    },
    avatarError() {
      console.log('加载头像失败')
    }
  },
  watch: {
    avatar(val) {
      this.avatarUrl = val
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader {
  .avatar {
    .img {
      border: 1px solid #eee;
      border-radius: 6px;
    }
  }

  .notice {
    font-size: 12px;
    color: #aaa;
  }
}
</style>
